// 主要JavaScript功能

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 自动隐藏消息提示
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);

    // 设置日期输入的最小值为今天
    var dateInputs = document.querySelectorAll('input[type="date"]');
    var today = new Date().toISOString().split('T')[0];
    dateInputs.forEach(function(input) {
        if (!input.value) {
            input.min = today;
        }
    });
    
    // 异步切换任务状态
    document.querySelectorAll('.toggle-status-btn').forEach(button => {
        button.addEventListener('click', function() {
            const taskId = this.dataset.taskId;
            const originalHtml = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            this.disabled = true;

            fetch(`/toggle_status/${taskId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const newStatus = data.new_status;
                    const statusBadge = document.getElementById(`task-status-${taskId}`);
                    const taskTitle = document.getElementById(`task-title-${taskId}`);

                    // 更新状态徽章
                    statusBadge.textContent = getStatusText(newStatus);
                    statusBadge.className = `status-badge status-${newStatus}`;

                    // 更新标题样式
                    if (newStatus === 'completed') {
                        taskTitle.classList.add('text-decoration-line-through', 'text-muted');
                    } else {
                        taskTitle.classList.remove('text-decoration-line-through', 'text-muted');
                    }
                    
                    // 更新卡片的完成状态样式
                    const taskCard = taskTitle.closest('.card');
                    if (newStatus === 'completed') {
                        taskCard.classList.add('completed-task');
                    } else {
                        taskCard.classList.remove('completed-task');
                    }
                    
                    showMessage('状态更新成功', 'success');
                } else {
                    showMessage(data.error || '更新失败', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('发生错误，请重试', 'danger');
            })
            .finally(() => {
                this.innerHTML = originalHtml;
                this.disabled = false;
            });
        });
    });
    
    // 恢复筛选状态
    restoreFilterState();
    
    // 监听搜索框的回车键事件
    var searchInput = document.getElementById('search');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.closest('form').submit();
            }
        });
    }
});

function getStatusText(status) {
    switch (status) {
        case 'todo':
            return '待办';
        case 'in_progress':
            return '进行中';
        case 'completed':
            return '已完成';
        default:
            return status;
    }
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 移除现有的消息
    var existingAlerts = document.querySelectorAll('.alert');
    existingAlerts.forEach(function(alert) {
        alert.remove();
    });

    // 创建新的消息元素
    var alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    // 插入到页面顶部
    var container = document.querySelector('.container-fluid');
    if (container) {
        container.insertBefore(alertDiv, container.firstChild);
    }

    // 自动隐藏
    setTimeout(function() {
        var bsAlert = new bootstrap.Alert(alertDiv);
        bsAlert.close();
    }, 5000);
}

// 表单验证
function validateForm(form) {
    var isValid = true;
    var requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(function(field) {
        if (!field.value.trim()) {
            field.classList.add('is-invalid');
            isValid = false;
        } else {
            field.classList.remove('is-invalid');
        }
    });

    return isValid;
}

// 为表单添加验证
document.querySelectorAll('form').forEach(function(form) {
    form.addEventListener('submit', function(e) {
        if (!validateForm(form)) {
            e.preventDefault();
            showMessage('请填写所有必填字段', 'warning');
        }
    });
});

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl+N 或 Cmd+N 添加新任务
    if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault();
        var addButton = document.querySelector('a[href*="add_task"]');
        if (addButton) {
            addButton.click();
        }
    }
    
    // ESC 键关闭模态框
    if (e.key === 'Escape') {
        var modals = document.querySelectorAll('.modal.show');
        modals.forEach(function(modal) {
            var bsModal = bootstrap.Modal.getInstance(modal);
            if (bsModal) {
                bsModal.hide();
            }
        });
    }
});

// 任务卡片动画
function animateTaskCards() {
    var cards = document.querySelectorAll('.task-card');
    cards.forEach(function(card, index) {
        card.style.animationDelay = (index * 0.1) + 's';
    });
}

// 页面加载时执行动画
window.addEventListener('load', function() {
    animateTaskCards();
});

// 本地存储功能
function saveToLocalStorage(key, value) {
    try {
        localStorage.setItem(key, JSON.stringify(value));
    } catch (e) {
        console.warn('无法保存到本地存储:', e);
    }
}

function getFromLocalStorage(key) {
    try {
        var item = localStorage.getItem(key);
        return item ? JSON.parse(item) : null;
    } catch (e) {
        console.warn('无法从本地存储读取:', e);
        return null;
    }
}

// 保存筛选条件
function saveFilterState() {
    var form = document.querySelector('form[method="GET"]');
    if (form) {
        var formData = new FormData(form);
        var filters = {};
        for (var [key, value] of formData.entries()) {
            filters[key] = value;
        }
        saveToLocalStorage('taskFilters', filters);
    }
}

// 恢复筛选条件
function restoreFilterState() {
    var filters = getFromLocalStorage('taskFilters');
    if (filters) {
        Object.keys(filters).forEach(function(key) {
            var input = document.querySelector(`[name="${key}"]`);
            if (input && !input.value) {
                input.value = filters[key];
            }
        });
    }
}

// 表单提交时保存筛选状态
document.addEventListener('submit', function(e) {
    if (e.target.method === 'get') {
        saveFilterState();
    }
});